package com.fan.gofast.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * @ClassName JsonUtil
 * @Decription
 * @Author jimware
 * @Date 23.1.3 0003 17:46
 **/
public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    public JsonUtil() {
    }



    public static String toJsonString(Object object)  {
        mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static <T> T fromJson(String jsonString, Class<T> clazz) {
        if (clazz.equals(String.class)) {
            return (T) jsonString;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            try {
                return StringUtils.isEmpty(jsonString) ? null : mapper.readValue(jsonString, clazz);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    public static <T> List<T> wapperStringToList(String jsonString, Class<T> clazz) {
        try {
            return (List)mapper.readValue(jsonString, getCollectionType(mapper, List.class, clazz));
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static <T> Set<T> wapperStringToSet(String jsonString, Class<T> clazz) throws IOException {
        return (Set)mapper.readValue(jsonString, getCollectionType(mapper, Set.class, clazz));
    }

    public static <T> T convertObjToPojo(Object object, Class<T> clazz) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.convertValue(object, clazz);
    }

    private static JavaType getCollectionType(ObjectMapper mapper, Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }


    public static void main(String[] args) throws IOException {
        System.out.println((String)fromJson("1,2,3", String.class));
    }
}
